package com.leyou.sms.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.constants.SmsConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.leyou.sms.constants.SmsConstants.*;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class SmsUtil {

    @Autowired
    private IAcsClient acsClient;
    @Autowired
    private SmsProperties prop;


    public void sendVerifyCode(String phone, String code) {
        try {
            sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(),
                    String.format(SmsConstants.VERIFY_CODE_PARAM_TEMPLATE, code));
        } catch (Exception e) {
            log.error("发送短信失败.", e);
        }
    }

    public void sendMessage(String phone, String signName, String templateCode, String templateParam) {
        // 准备请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(prop.getDomain());
        request.setSysVersion(prop.getVersion());
        request.setSysAction(prop.getAction());
        request.putQueryParameter(SMS_PARAM_KEY_PHONE, phone);
        request.putQueryParameter(SMS_PARAM_KEY_SIGN_NAME, signName);
        request.putQueryParameter(SMS_PARAM_KEY_TEMPLATE_CODE, templateCode);
        request.putQueryParameter(SMS_PARAM_KEY_TEMPLATE_PARAM, templateParam);

        try {
            // 发起请求，得到响应
            CommonResponse response = acsClient.getCommonResponse(request);
            // 解析发送结果
            String json = response.getData();
            Map<String, String> data = JsonUtils.toMap(json, String.class, String.class);
            // 判断
            if (!OK.equals(data.get(SMS_RESPONSE_KEY_CODE))) {
                // 失败了

                throw new LyException(500, data.get(SMS_RESPONSE_KEY_MESSAGE));
            }
            // 发送成功
            log.info("发送短信成功！");
        } catch (ClientException e) {
            throw new LyException(500, e);
        }
    }
}
